
package com.leetcode.stack;

import java.util.Deque;
import java.util.LinkedList;

/**
 * Solution20
 */
public class Solution20 {

    public static void main(String[] args) {

        Solution20 s = new Solution20();
        String str = "}";
        System.out.println(s.isValid(str));
    }

    public boolean isValid(String s) {

        if (s == null || s.length() <= 0) {
            return false;
        }

        Deque<Character> stack = new LinkedList<>();

        for (int i = 0; i < s.length(); ++i) {
            if (stack.isEmpty()) {
                stack.push(s.charAt(i));
                continue;
            }
            switch (s.charAt(i)) {
                case '(':
                case '{':
                case '[':
                    stack.push(s.charAt(i));
                    break;
                case ')':
                    if (stack.peek() == '(') {
                        stack.pop();
                    } else {
                        stack.push(s.charAt(i));
                    }
                    break;
                case ']':
                    if (stack.peek() == '[') {
                        stack.pop();
                    } else {
                        stack.push(s.charAt(i));
                    }
                    break;
                case '}':
                    if (stack.peek() == '{') {
                        stack.pop();
                    } else {
                        stack.push(s.charAt(i));
                    }
                    break;
                default:
                    break;
            }
        }

        return stack.isEmpty();

    }
}